﻿/////////////////////////////////////////////////
//文件名:FileTransfer
//描  述:
//创建者:刘凡平(Iveely Liu)
//邮  箱:945222889@qq.com
//组  织:Iveely
//年  份:2012/5/11 13:03:50
///////////////////////////////////////////////


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace IveelySE.BigData.Common.Communication
{
    /// <summary>
    /// 传送器
    /// </summary>
    public class Transfer
    {
        /// <summary>
        /// 服务端
        /// </summary>
        public class Server
        {
            /// <summary>
            /// 声明用户输入信息处理事件委托
            /// </summary>
            /// <param name="message">用户传递的消息</param>
            /// <returns>返回处理结果</returns>
            public delegate PObject dealWith(byte[] message);

            private static readonly object SyncRoot = new object();
            /// <summary>
            /// 监听状态
            /// </summary>
            private bool onListening { get; set; }
            /// <summary>
            /// 构造方法
            /// </summary>
            /// <param name="ip">IP地址</param>
            /// <param name="port">端口号</param>
            public Server(IPAddress ip, int port)
            {
                //监听状态false
                onListening = false;
                //IP地址
                Address = ip;
                //端口
                Port = port;
            }
            /// <summary>
            /// 监听器
            /// </summary>
            private TcpListener Listener { get; set; }
            /// <summary>
            /// IP地址
            /// </summary>
            private IPAddress Address { get; set; }
            /// <summary>
            /// IP端口
            /// </summary>
            private int Port { get; set; }
            /// <summary>
            /// 监听
            /// </summary>
            public void Listen(ref byte[] msg,dealWith deal)
            {
                try
                {
                    lock (SyncRoot)
                    {
                        //初始化监听器
                        Listener = new TcpListener(Address, Port);
                        //启动监听服务
                        Listener.Start();
                        //监听中
                        onListening = true;
                    }
                    //等待客户端链接
                    TcpClient client = Listener.AcceptTcpClient();
                    //提示信息
                    Common.Printf.WriteInfo("处理客户端:"+client.Client.RemoteEndPoint.ToString());
                    //处理客户端程序
                    ProcessClient(client, ref msg,deal);
                }
                catch(Exception ex)
                {
                    Common.Log.Write(ex.Message);
                }
                finally
                {
                    //关闭监听
                   StopListening();
                }
            }

            /// <summary>
            /// 关闭监听
            /// </summary>
            public void StopListening()
            {
                //如果在监听
                if (onListening)
                {
                    lock (SyncRoot)
                    {
                        //设置为非监听状态
                        onListening = false;
                        //关闭监听器
                        Listener.Stop();
                    }
                }
            }

            /// <summary>
            /// 处理客户端的连接
            /// </summary>
            /// <param name="client">客户端</param>
            /// <param name="msg">处理的信息</param>
            /// <param name="deal">处理信息使用的方法</param>
            private void ProcessClient(TcpClient client, ref byte[] msg,dealWith deal)
            {
                try
                {
                    //字节数组容器
                    var bytes = new byte[10240];
                    //读取网络流
                    using (NetworkStream netStream = client.GetStream())
                    {
                        //设定读超时
                        netStream.ReadTimeout = 600000;
                        netStream.Read(msg, 0, msg.Length);
                        //放入数组容器
                        bytes = msg;
                        //执行搜索
                        // string result = message.ToString();
                        // msg = Common.Serialize.Obj2Byte( result);
                        //Console.WriteLine(result);
                        //建立回复对象
                        PObject obj = deal(msg);
                        //转换为字节数组
                        bytes = Common.Serialize.Obj2Byte(obj);
                        //执行回复
                        netStream.Write(bytes, 0, bytes.Length);
                       
                    }
                }
                finally
                {
                    //如果客户端不为空
                    if (client != null)
                    {
                        //记住关闭
                        client.Close();
                    }
                }
            }
        }

        /// <summary>
        /// 客户端
        /// </summary>
        public class Client
        {
            /// <summary>
            /// 终端
            /// </summary>
            private readonly IPEndPoint endPoint;
            /// <summary>
            /// 构造方法
            /// </summary>
            /// <param name="ip">服务器IP</param>
            /// <param name="port">服务器访问端口</param>
            public Client(IPAddress ip, int port)
            {
                //实例化终端
                endPoint = new IPEndPoint(ip, port);
            }
            /// <summary>
            /// 链接到服务器
            /// </summary>
            /// <param name="msg">发送给服务器的信息</param>
            /// <returns>返回发送状态</returns>
            public object ConnectToServer(Object msg)
            {
                PObject result = null;
                TcpClient client = null;
                try
                {
                    //连接到终端
                    client = new TcpClient();
                    client.Connect(endPoint);
                    //将即将发送的消息转换为字节数组
                    byte[] bytes = Serialize.Obj2Byte(msg);
                    // 获取和服务端会话的流
                    using (NetworkStream netStream = client.GetStream())
                    {
                        //发送消息
                        netStream.Write(bytes, 0, bytes.Length);
                        // 获得响应
                        // 存储响应内容的缓存
                        // bytes = new byte[10240];
                        //result=Common.Serialize.Byte2Obj(bytes);
                        ////获取响应消息
                        netStream.Read(bytes, 0, bytes.Length);
                        result = (PObject)Common.Serialize.Byte2Obj(bytes);
                        
                        ////转换为字符串
                        //string serverResponse = Encoding.UTF8.GetString(bytes, 0, bytesRead);
                        //result = serverResponse;
                    }
                }
                catch
                {
                    //0表示不能链接成功或是存在异常
                    ;
                }
                finally
                {
                    //如果客户端还在
                    if (client != null)
                        //关闭
                        client.Close();
                }
                //返回结果
                return result;
            }
        }
    }
}
